import { createSlice } from "@reduxjs/toolkit";

const URL = "http://geek.itheima.net/v1_0/channels";

const channelStore = createSlice({
  name: "channel",
  // 初始化 state
  initialState: {
    channelList: [],
  },
  // 修改数据的方法,同步方法
  reducers: {
    setChannels(state, action) {
      state.channelList = action.payload;
    },
  },
});

const { setChannels } = channelStore.actions;

const reducer = channelStore.reducer;

// 修改数据的方法,异步方法
const fetchGetChannels = () => {
  return async (dispatch) => {
    // 异步操作
    const res = await fetch(URL);
    const listRes = await res.json();
    // 调用同步方法
    dispatch(setChannels(listRes.data.channels));
  };
};

// 以按需导出的方式导出 actionCreater
export { setChannels, fetchGetChannels };

//以默认导出的方式导出 reducer
export default reducer;
